<?php
namespace app\common\model;
use think\Model;
use think\model\concern\SoftDelete;

class Page extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    protected $autoWriteTimestamp = true;

    /**
     * 初始化
     */
    static function init()
    {
        $list = Category::where('model',2)->select();
        foreach ($list as $r){
            $data = self::where('cid',$r['id'])->find();
            if(empty($data)){
                self::create([
                   'cid'  => $r['id'],
                   'title'=> $r['name'],
                ]);
            }
        }
        parent::init(); // TODO: Change the autogenerated stub
    }

    /**
     * 关联分类
     * @return \think\model\relation\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'cid', 'id')->bind(['category_name'=>'name']);
    }

    /**
     * 新增后更新URL
     * @param Model $data
     * @return bool
     */
    public static function onAfterInsert($data)
    {
        if($data['is_link'] == 1){
            return true;
        }else{
            $url = '/page/'.$data['id'].'.html';
            self::where(['id'=>$data['id']])->update(['url'=>$url]);
            return true;
        }
    }
    /**
     * 新增后更新URL
     * @param Model $data
     * @return bool
     */
    public static function onAfterUpdate($data)
    {
        if($data['is_link'] == 1){
            return true;
        }else{
            $url = '/page/'.$data['id'].'.html';
            self::where(['id'=>$data['id']])->update(['url'=>$url]);
            return true;
        }
    }

    /**
     * 获取列表
     * @return \think\Collection
     */
    static function lists()
    {
        return self::where('status','1')->select();
    }
    
}